#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include <iostream>
#include <cstdlib>
#include <strings.h>
#include <cstring>
#include <string>
#include <sstream>
 

using namespace std;

void error(string msg)
{
    cout <<msg;
    exit(0);
}

int main(int argc, char *argv[])
{

    enum oper{Sm, Rs, Dv, Mp, Ex,Rz };
    int sockfd, portno, n;

    struct sockaddr_in serv_addr;
    struct hostent *server;


    char buffer[256];
    if (argc < 3) {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");



	char sum1[50], sum2[50], ope[2];
	string op;
	cout << "[Sm]Suma, [Rs]Resta, [Dv]División, [Mp]Multiplicación, [Ex]Exponente, [Rz]Raiz" << endl;
	cin >> op;
	if (op=="Sm" ) sprintf(ope,"%d", Sm);
	else if (op=="Rs" ) sprintf(ope,"%d", Rs);
	else if (op=="Dv" ) sprintf(ope,"%d", Dv);
	else if (op=="Mp" ) sprintf(ope,"%d", Mp);
	else if (op=="Ex" ) sprintf(ope,"%d", Ex);
	else if (op=="Rz" ) sprintf(ope,"%d", Rz);

	cout << "Enter the first number: " << endl;
	cin >> sum1;

	if(op!="Rz")
	{
		cout << "Enter the second one: " << endl;
		cin >> sum2;
	}

	stringstream temp1;
	temp1 << ope <<"."<<sum1<<"."<<sum2<<'\0';
	string temp2 = temp1.str();
	//cout <<"T2: " << temp2 <<endl; Perfect
    	n = write(sockfd,temp2.c_str(),temp2.size());
	// cout << n << endl; Perfect
	if (n<0)
        	error("ERROR writing from socket (client)\n");
	
	n = read(sockfd,buffer,225);
	// <<"Read: " << n << " Buffer: " << buffer << endl;

	if (n<0)
        	error("ERROR reading from socket (client)\n");

	printf("%s\n",buffer);
    	return 0;
}
